package role

import (
	"context"
	"go-zero-project/services/user/rpc/internal/mapper"
	"go-zero-project/services/user/rpc/internal/svc"
	"go-zero-project/services/user/rpc/pb"
	"gorm.io/gorm"

	"github.com/zeromicro/go-zero/core/logx"
)

type DeleteRoleLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewDeleteRoleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeleteRoleLogic {
	return &DeleteRoleLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *DeleteRoleLogic) DeleteRole(in *pb.DeleteRoleReq) (*pb.EmptyObj, error) {
	// begin Transaction ...
	err := l.svcCtx.DBEngin.Transaction(func(tx *gorm.DB) error {
		// 1.delete role info
		deleteRoleErr := mapper.NewRoleMapper().DeleteRoleId(tx, in.RoleIdArr)
		if deleteRoleErr != nil {
			return deleteRoleErr
		}
		// 2.delete role menu info
		deleteRoleMenuArr := mapper.NewRoleMenuMapper().DeleteRoleMenu(tx, in.RoleIdArr)
		if deleteRoleMenuArr != nil {
			return deleteRoleMenuArr
		}
		// 3.delete role dept info
		deleteRoleDeptErr := mapper.NewRoleDeptMapper().DeleteRoleDept(tx, in.RoleIdArr)
		if deleteRoleDeptErr != nil {
			return deleteRoleDeptErr
		}
		// 4.delete role user info
		deleteRoleUserErr := mapper.NewUserRoleMapper().DeleteRoleUser(tx, in.RoleIdArr)
		if deleteRoleUserErr != nil {
			return deleteRoleUserErr
		}
		return nil
	})
	if err != nil {
		return nil, err
	}
	return &pb.EmptyObj{}, nil
}
